import { animation, AnimationClip, resources, Sprite, SpriteFrame } from "cc";
//import DataManager from "../Global/DataManager";
import { ResourceManager } from "../Core/ResourceManager";

import StateMachine from "./StateMachine";
import { Core } from "../Core/Core";

import { PicPath } from "../Config/ResourceConfig";
import { sortSpriteFrame } from "../Util";

/***
 * unit:milisecond
 */
export const ANIMATION_SPEED = 1 / 3;

/***
 * 状态（每组动画的承载容器，持有SpriteAnimation组件执行播放）
 */
export default class State {
  public isReady = false; // 资源加载状态标志
  private animationClip: AnimationClip;
  constructor(
    private fsm: StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
    private force: boolean = false,
    private speed: number = 1
  ) {
    // 直接加载整个目录下的图片资源
    //  ResourceManager.Instance.loadDirRes<SpriteFrame>(PicPath[this.path], SpriteFrame)
    //   .then(spriteFrames => {
    //     console.log("111spriteFrames in State constructor", spriteFrames);
    //     this.createAnimation(spriteFrames);
    //     this.isReady = true; // 标记资源加载完成

    //     // 如果状态机正在等待这个状态，立即运行
    //     if (this.fsm.pendingState === this) {
    //       console.log("111Applying pending state for path:", this.path);
    //       this.fsm.applyPendingState();
    //     }
    //   })
    //   .catch(error => {
    //     console.error(`Failed to load resources for ${this.path}:`, error);
    //   });

    // 同步加载资源
    // 使用 resources.loadDir 加载资源
        // 获取动画对应的目录路径
        const dirPath = PicPath[this.path];
        console.log("this.path", this.path);
        console.log("PicPath[this.path]", PicPath[this.path]);
        // 同步获取精灵帧
        const spriteFrames = ResourceManager.Instance.getDirRes<SpriteFrame>(dirPath);
        //console.log("同步加载dirPath in State constructor", dirPath);
        //console.log("同步加载 spriteFrames in State constructor", spriteFrames);
        
        if (!spriteFrames || spriteFrames.length === 0) {
            console.error(`找不到精灵帧: ${dirPath}`);
            return;
        }
        this.createAnimation(spriteFrames);


    }

  // 添加异步加载方法
  load(): Promise<void> {
    return new Promise((resolve, reject) => {
      resources.loadDir(
        PicPath[this.path],
        SpriteFrame,
        (err: Error | null, assets: SpriteFrame[]) => {
          if (err) return reject(err);
          this.createAnimation(assets);
          resolve();
        }
      );
    });
  }

  private createAnimation(spriteFrames: SpriteFrame[]) {

    const track = new animation.ObjectTrack();
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty("spriteFrame");
    //const spriteFrames = Core.Instance.textureMap.get(this.path);
    // const spriteFrames = ResourceManager.Instance.loadRes(PicPath[this.path], SpriteFrame);
    // console.log("this.path", this.path);
    // console.log("spriteFrames", spriteFrames);
    const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteFrames).map((item, index) => [index * this.speed, item]);
    // console.log("frames", frames);
    track.channel.curve.assignSorted(frames);

    //动画添加轨道
    this.animationClip = new AnimationClip();
    this.animationClip.name = this.path;
    this.animationClip.duration = frames.length * this.speed;
    this.animationClip.addTrack(track);
    this.animationClip.wrapMode = this.wrapMode;

  }

  run() {
    
    if (this.fsm.animationComponent.defaultClip?.name === this.animationClip.name && !this.force) {
      return;
    }
    this.fsm.animationComponent.defaultClip = this.animationClip;
    this.fsm.animationComponent.play();
  }
}
